package com.atguigu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {

    static DruidDataSource dataSource;
    static ThreadLocal<Connection> conns = new ThreadLocal<Connection>();


    static {
        try {
            //创建属性配置类
            Properties properties = new Properties();

            //从src源码目录下读取jdbc.properties
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");

            // 从流中加载键值对
            properties.load(resourceAsStream);

            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

//            System.out.println(dataSource.getConnection());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从数据库连接池中获取连接
     *
     * @return 返回null, 获取连接失败 <br/> 有值就成功
     */
    public static Connection getConnection() {
        Connection conn = conns.get();

        if (conn == null) {
            try {
                //从数据库连接池中获取连接
                conn = dataSource.getConnection();

                conns.set(conn);//关联连接到ThreadLocal中

                conn.setAutoCommit(false); // 设置手动管理事务

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return conn;
    }

    /**
     * 提交事务并关联连接
     */
    public static void commitAndClose() {
        Connection connection = conns.get();
        if (connection != null) {
            try {
                // 提交事务
                connection.commit();
                // 关闭连接/释放资源
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // 因为Tomcat服务器底层使用了线程池技术.一定要移除关联.否则报错
        conns.remove();
    }


    /**
     * 回滚事务并关联连接
     */
    public static void rollbackAndClose() {
        Connection connection = conns.get();
        if (connection != null) {
            try {
                // 提交事务
                connection.rollback();
                // 关闭连接/释放资源
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // 因为Tomcat服务器底层使用了线程池技术.一定要移除关联.否则
        conns.remove();
    }

    /**
     * 关闭连接/放回池中
     *
     * @param conn 需要释放的连接
     */
//    public static void closeConnection(Connection conn) {
//        if (conn != null) {
//            try {
//                conn.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//        }
//    }

}
